import {getPageMeta} from "@/services/request/meta";

export enum META_DATA_TYPE  {
	search = 'search_column',
	tableColumn = 'table_column',
	tableOperationButton = 'table_button'
}
/**
 * 从页面配置的meta里面获取特定类型的meta，并且排序
 * */
export function getSortedMetasByType(pageMeta: any[], type: META_DATA_TYPE): any[] {
	const tempArr = pageMeta.filter((item) => item.type === type);
	return tempArr.sort((a, b) => {
		try {
			const sa = a.props.sequence;
			const sb = b.props.sequence;
			if(
				(typeof sa === 'number')
				&&
				(!isNaN(sa))
				&&
				(typeof sb === 'number')
				&&
				(!isNaN(sb))
			) {
				return sa - sb;
			} else {
				return 0;
			}
		} catch (e) {
			return 0;
		}

	})
}

/**
 * 根据页面编码查询这个页面的metas
 * */
export function queryMetasByPageCode(pageCode: string): Promise<any[]> {
	return getPageMeta(pageCode).then((res: any) => {
		if(res.success) {
			return res.result && res.result.pageDatas || []
		} else {
			throw new Error(res.message);
		}
	})
}

/**
 * 根据页面编码查询metas，返回排序和分类后的metas
 * */
export async function getAllTypesOfMetasByPageCode(pageCode: string): Promise<{searchMetas: any[], tableColumnMetas: any[], tableOperationMetas: any[]}> {
	const metas = await queryMetasByPageCode(pageCode);
	return {
		searchMetas: getSortedMetasByType(metas, META_DATA_TYPE.search),
		tableColumnMetas: getSortedMetasByType(metas, META_DATA_TYPE.tableColumn),
		tableOperationMetas: getSortedMetasByType(metas, META_DATA_TYPE.tableOperationButton)
	}
}

/**
 * 从meta里面根据属性名称获取label
 * */
export function getLabelFromMetaArr(metaArr: any[], name: string) {
	return metaArr.find((item) => item.key === name)?.label || ''
}
